<template>
  <div class="tags-page">
    <el-page-header>
      <template slot="content">
        <h1>标签管理</h1>
        <p>管理和浏览包标签</p>
      </template>
    </el-page-header>
    
    <el-card class="tags-card">
      <template slot="header">
        <div class="card-header">
          <span>标签列表</span>
          <el-button type="primary" size="small" @click="showCreateTagDialog">新增标签</el-button>
        </div>
      </template>
      
      <div class="search-container" style="margin-bottom: 16px;">
        <el-input 
          v-model="searchQuery"
          placeholder="搜索标签名称"
          prefix-icon="el-icon-search"
          style="width: 300px;"
          @keyup.enter.native="searchTags"
        />
        <el-button type="primary" style="margin-left: 16px;" @click="searchTags">搜索</el-button>
      </div>
      
      <div v-if="loading" class="loading-container">
        <el-loading-spinner />
      </div>
      
      <div v-else-if="tags.length === 0" class="empty-state">
        <p>暂无标签数据</p>
      </div>
      
      <div v-else class="tags-grid">
        <div 
          v-for="tag in tags"
          :key="tag.id"
          class="tag-item"
        >
          <el-card :body-style="{ padding: '16px' }">
            <div class="tag-content">
              <div class="tag-header">
                <h3 class="tag-name">{{ tag.name }}</h3>
                <div class="tag-actions">
                  <el-button 
                    type="text" 
                    size="small" 
                    @click.stop="editTag(tag)"
                    icon="el-icon-edit"
                  />
                  <el-button 
                    type="text" 
                    size="small" 
                    danger 
                    @click.stop="deleteTag(tag.id)"
                    icon="el-icon-delete"
                  />
                </div>
              </div>
              
              <div class="tag-meta">
                <span class="package-count">📦 {{ tag.packageCount || 0 }} 个包</span>
                <span class="create-time">创建于 {{ formatDate(tag.createdAt) }}</span>
              </div>
              
              <div v-if="tag.description" class="tag-description">
                {{ tag.description }}
              </div>
              
              <div class="tag-footer">
                <el-button 
                  type="default" 
                  size="small" 
                  @click="viewPackagesByTag(tag.id)"
                >
                  查看相关包
                </el-button>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </el-card>
    
    <!-- 创建/编辑标签对话框 -->
    <el-dialog 
      :title="isEditing ? '编辑标签' : '创建标签'"
      :visible.sync="tagDialogVisible"
      width="500px"
    >
      <el-form 
        ref="tagForm"
        :model="tagForm"
        :rules="tagRules"
        label-width="80px"
      >
        <el-form-item label="标签名称" prop="name">
          <el-input v-model="tagForm.name" placeholder="请输入标签名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="tagForm.description" type="textarea" placeholder="请输入标签描述（可选）" />
        </el-form-item>
        <el-form-item label="颜色">
          <el-color-picker v-model="tagForm.color" :predefine="predefineColors" size="small" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="tagDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveTag">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'TagsPage',
  layout: 'default',
  data() {
    return {
      tags: [],
      loading: false,
      searchQuery: '',
      
      // 标签表单相关
      tagDialogVisible: false,
      isEditing: false,
      currentTagId: null,
      tagForm: {
        name: '',
        description: '',
        color: '#1890ff'
      },
      tagRules: {
        name: [
          { required: true, message: '请输入标签名称', trigger: 'blur' },
          { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
        ],
        description: [
          { max: 200, message: '描述不能超过 200 个字符', trigger: 'blur' }
        ]
      },
      
      // 预定义颜色
      predefineColors: [
        '#1890ff', '#52c41a', '#faad14', '#f5222d',
        '#722ed1', '#eb2f96', '#13c2c2', '#fa8c16',
        '#a0d911', '#52c41a', '#722ed1', '#1890ff'
      ]
    }
  },
  async fetch() {
    await this.loadTags()
  },
  methods: {
    async loadTags() {
      this.loading = true
      try {
        let endpoint = '/tags'
        if (this.searchQuery) {
          endpoint += `?query=${encodeURIComponent(this.searchQuery)}`
        }
        
        const response = await this.$axios.get(endpoint)
        this.tags = response || []
      } catch (error) {
        this.$message.error('加载标签失败：' + error.message)
        this.tags = []
      } finally {
        this.loading = false
      }
    },
    
    searchTags() {
      this.loadTags()
    },
    
    formatDate(dateString) {
      if (!dateString) return '未知'
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      })
    },
    
    showCreateTagDialog() {
      this.isEditing = false
      this.currentTagId = null
      this.resetTagForm()
      this.tagDialogVisible = true
    },
    
    async editTag(tag) {
      this.isEditing = true
      this.currentTagId = tag.id
      
      try {
        const response = await this.$axios.get(`/tags/${tag.id}`)
        const tagDetails = response
        
        this.tagForm = {
          name: tagDetails.name,
          description: tagDetails.description || '',
          color: tagDetails.color || '#1890ff'
        }
        
        this.tagDialogVisible = true
      } catch (error) {
        this.$message.error('加载标签详情失败：' + error.message)
      }
    },
    
    resetTagForm() {
      this.tagForm = {
        name: '',
        description: '',
        color: '#1890ff'
      }
      
      if (this.$refs.tagForm) {
        this.$refs.tagForm.resetFields()
      }
    },
    
    async saveTag() {
      this.$refs.tagForm.validate(async (valid) => {
        if (valid) {
          try {
            if (this.isEditing) {
              await this.$axios.put(`/tags/${this.currentTagId}`, this.tagForm)
              this.$message.success('标签更新成功')
            } else {
              await this.$axios.post('/tags', this.tagForm)
              this.$message.success('标签创建成功')
            }
            
            this.tagDialogVisible = false
            await this.loadTags()
          } catch (error) {
            this.$message.error('保存失败：' + error.message)
          }
        }
      })
    },
    
    async deleteTag(id) {
      this.$confirm('确定要删除这个标签吗？删除后，相关的包将不再包含此标签。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await this.$axios.delete(`/tags/${id}`)
          this.$message.success('删除成功')
          await this.loadTags()
        } catch (error) {
          this.$message.error('删除失败：' + error.message)
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    
    viewPackagesByTag(tagId) {
      this.$router.push({ path: '/packages', query: { tagId } })
    }
  }
}
</script>

<style scoped>
.tags-page {
  padding: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-container {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #8c8c8c;
}

.tags-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 16px;
}

.tag-item {
  transition: all 0.3s ease;
}

.tag-item:hover {
  transform: translateY(-2px);
}

.tag-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.tag-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.tag-name {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
  color: #262626;
}

.tag-actions {
  display: flex;
  gap: 4px;
}

.tag-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #8c8c8c;
  margin-bottom: 12px;
}

.tag-description {
  font-size: 14px;
  color: #595959;
  line-height: 1.5;
  margin-bottom: 16px;
  flex: 1;
}

.tag-footer {
  margin-top: auto;
}
</style>